<template>
  <el-dialog v-model="visible" :title="title" width="1200px">
    <el-form :model="form" label-width="8em">
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="form.name" placeholder="输入模板名称" />
      </el-form-item>
      <el-form-item label="计费方式" prop="billing_method">
        <el-radio-group v-model="form.type">
          <el-radio v-for="(method, index) in billingMethodList" :key="index" :value="method.value">
            {{ method.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="配送区域及运费" prop="">
        <el-table border :data="form.domains">
          <el-table-column label="可配送区域" width="300px">
            <template #default="{ row }">
              <p v-if="row.is_global">默认全国(开启指定区域不配送时失效)</p>
              <CitySelect v-else v-model="row.address_ids" />
            </template>
          </el-table-column>
          <el-table-column :label="`首${formatBillingMethodUnit}`">
            <template #default="{ row }">
              <el-input v-model="row.first_unit" type="number" placeholder="输入首件" />
            </template>
          </el-table-column>
          <el-table-column label="运费(元)">
            <template #default="{ row }">
              <el-input v-model="row.first_amount" type="number" placeholder="输入运费" />
            </template>
          </el-table-column>
          <el-table-column :label="`续${formatBillingMethodUnit}`">
            <template #default="{ row }">
              <el-input v-model="row.next_unit" type="number" placeholder="输入续件运费" />
            </template>
          </el-table-column>
          <el-table-column label="续费(元)">
            <template #default="{ row }">
              <el-input v-model="row.next_amount" type="number" placeholder="输入续件运费" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button v-if="!row.is_global" type="danger" @click="handleDeleteArea(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button style="margin-top: 10px" type="primary" icon="plus" @click="handleAddArea">
          单独添加配送区域
        </el-button>
      </el-form-item>
      <el-form-item label="指定包邮" prop="free_shipping">
        <el-switch v-model="form.enable_free" />
        <template v-if="form.enable_free">
          <el-table border :data="form.free_domains">
            <el-table-column label="选择地区">
              <template #default="{ row }">
                <CitySelect v-model="row.address_ids" />
              </template>
            </el-table-column>
            <el-table-column :label="`包邮${formatBillingMethodUnit}`">
              <template #default="{ row }">
                <el-input v-model="row.free_unit" type="number" placeholder="输入包邮" />
              </template>
            </el-table-column>
            <el-table-column label="包邮金额(元)">
              <template #default="{ row }">
                <el-input v-model="row.free_amount" type="number" placeholder="输入金额" />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="danger" @click="handleDeleteFree(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button style="margin-top: 10px" type="primary" icon="plus" @click="handleAddFree">
            单独添加指定包邮
          </el-button>
        </template>
      </el-form-item>
      <el-form-item label="指定不送达" prop="non_delivery">
        <el-switch v-model="form.enable_no_service" />
        <template v-if="form.enable_no_service">
          <el-table border :data="form.no_service_domains">
            <el-table-column label="可配送区域">
              <template #default="{ row }">
                <CitySelect v-model="row.address_ids" />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="danger" @click="handleDeleteNon(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button style="margin-top: 10px" type="primary" icon="plus" @click="handleAddNon">
            单独添加指定不送达
          </el-button>
        </template>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sequence" type="number" placeholder="输入排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="el-dialog__footer">
        <el-button type="default" @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  ShippingTemplateIetmType,
  ShippingTemplateCreateType,
  ShippingTemplateDomainType,
  ShippingTemplateFreeDomainType,
  ShippingTemplateNoServiceDomainType,
} from "@/api/goods/shipping-template";
import CitySelect from "@/components/CitySelect/index.vue";
import { useShippingTemplateStoreHook } from "@/store/modules/goods/shipping-template";
import { cloneDeep } from "lodash-es";

export type FormType = "add" | "edit";

export type Props = {
  type: FormType;
};

const shippingTemplateStore = useShippingTemplateStoreHook();

const visible = defineModel<boolean>();

const props = defineProps<Props>();

const emits = defineEmits(["confirm"]);

const billingMethodList = ref<{ label: string; value: ShippingTemplateIetmType }[]>([
  {
    label: "按件数计费",
    value: "quantity",
  },
  {
    label: "按体积计费",
    value: "volume",
  },
  {
    label: "按重量计费",
    value: "weight",
  },
]);

const defaultForm = cloneDeep<ShippingTemplateCreateType>({
  name: "",
  type: "quantity",
  enable_free: false,
  enable_no_service: false,
  sequence: 0,
  domains: [
    {
      address_ids: [],
      first_unit: 1,
      first_amount: 0,
      next_unit: 0,
      next_amount: 0,
      is_global: true,
    },
  ],
  free_domains: [],
  no_service_domains: [],
});

const form = reactive<ShippingTemplateCreateType>(defaultForm);

const formatBillingMethodUnit = computed(() => {
  switch (form.type) {
    case "quantity":
      return "件数";
    case "volume":
      return "体积(m³)";
    case "weight":
      return "重量(KG)";
  }
});

const title = computed(() => {
  return props.type === "add" ? "添加模板" : "编辑模板";
});

function handleAddArea() {
  form.domains.push({
    address_ids: [],
    first_unit: 1,
    first_amount: 0,
    next_unit: 0,
    next_amount: 0,
    is_global: false,
  });
}

function handleAddFree() {
  form.free_domains.push({
    address_ids: [],
    free_unit: 0,
    free_amount: 0,
  });
}

function handleAddNon() {
  form.no_service_domains.push({
    address_ids: [],
  });
}

function handleDeleteArea(row: ShippingTemplateDomainType) {
  form.domains.splice(form.domains.indexOf(row), 1);
}

function handleDeleteFree(row: ShippingTemplateFreeDomainType) {
  form.free_domains.splice(form.free_domains.indexOf(row), 1);
}

function handleDeleteNon(row: ShippingTemplateNoServiceDomainType) {
  form.no_service_domains.splice(form.no_service_domains.indexOf(row), 1);
}

async function handleConfirm() {
  if (form.name?.length == 0) {
    ElMessage.error("请输入模板名称");
    return;
  }
  if (form.domains.some((i) => i.first_unit < 1)) {
    ElMessage.error(`${formatBillingMethodUnit.value}应大于0`);
    return;
  }
  if (form.domains.some((i) => i.next_unit < 1)) {
    ElMessage.error(`续${formatBillingMethodUnit.value}应大于0`);
    return;
  }
  if (form.free_domains.some((i) => i.free_unit < 1)) {
    ElMessage.error(`包邮${formatBillingMethodUnit.value}应大于0`);
    return;
  }
  if (props.type == "add") {
    await shippingTemplateStore.fetchCreateShippingTemplate(form);
    emits("confirm");
    visible.value = false;
  }
}
</script>

<style scoped lang="scss"></style>
